package cn.bestick.cblog.servlet.admin;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.bestick.cblog.dto.AboutDto;
import cn.bestick.cblog.service.ArticleService;
import cn.bestick.cblog.service.impl.ArticleServiceImpl;

public class AboutManageServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private ArticleService articleService = new ArticleServiceImpl();

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.service(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		this.service(request, response);
	}

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String action = request.getParameter("action");

		if ("preSave".equals(action)) {
			preSave(request, response);
		} else if ("save".equals(action)) {
			save(request, response);
		} else {
			show(request, response);
		}
	}

	private void save(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String content = request.getParameter("content");
		AboutDto article = articleService.getAbout();
		article.setContent(content);
		articleService.updateAbout(article);
		request.setAttribute("article", article);
		request.setAttribute("mainPage", "template/about/manage-detail.jsp");
		request.getRequestDispatcher("manage.jsp").forward(request, response);

	}

	private void show(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		AboutDto article = articleService.getAbout();
		request.setAttribute("article", article);
		request.setAttribute("mainPage", "template/about/manage-detail.jsp");
		request.getRequestDispatcher("manage.jsp").forward(request, response);
	}

	private void preSave(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		AboutDto article = articleService.getAbout();
		request.setAttribute("article", article);
		request.setAttribute("mainPage", "template/about/manage-save.jsp");
		request.getRequestDispatcher("manage.jsp").forward(request, response);
	}
}
